from django.contrib.auth.backends import ModelBackend
import re
from apps.user.models import User
from itsdangerous import URLSafeTimedSerializer
from django.conf import settings
from .constants import VERIFY_EMAIL_TOKEN_EXPIRES


def get_user_by_account(account):
    try:
        if re.match(r"^1[3-9]\d{9}", account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except:
        # 如果报错 返回None
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    # request 参数必须带上
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 根据用户名/手机号获取用户
        # 验证密码是否正确
        # 返回user用户
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None


# 生成邮箱激活链接
def generate_verify_email_url(user):
    s = URLSafeTimedSerializer(settings.SECRET_KEY)
    data = {"user_id": user.id, 'email': user.email}
    token = s.dumps(data)
    print(settings.EMAIL_VERIFY_URL + '?token=' + token)
    return settings.EMAIL_VERIFY_URL + '?token=' + token

# 反序列化获取token
def check_verify_email_token(token):
    s = URLSafeTimedSerializer(settings.SECRET_KEY)
    try:
        data = s.loads(token)
    except:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user
